package cloudspace.vm.javassist;

import java.net.URL;
import java.util.List;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.Translator;
import cloudspace.vm.VM;

/**
 * The Class ConfigurableTranslator. This is a special translator that can be
 * configured with a configuration file.
 */
public class ConfigurableTranslatorLoader implements Translator
{

	/** The custom expr. */
	private CustomExprEditor cusExpr;

	/**
	 * Instantiates a new configurable translator.
	 * 
	 * @param current
	 *            the current
	 */
	public ConfigurableTranslatorLoader(ConfigParser current)
	{
		List<CommandInterface> editConfigs = current.getCommands();
		cusExpr = new CustomExprEditor(editConfigs);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javassist.Translator#onLoad(javassist.ClassPool, java.lang.String)
	 */
	@Override
	public void onLoad(ClassPool pool, String classname)
			throws NotFoundException, CannotCompileException
	{
		try
		{
			CtClass clazz = pool.get(classname);
			if (classname.startsWith("auto.generated."))
			{
				rewriteClass(clazz);
			}
			else
			{
				if(VM.getThreadTag().isLocalClass(classname))
				{
					rewriteClass(clazz);
				}
			}

		}
		catch (NotFoundException e)
		{
			// Do nothing here. This just means that the class is in a loader
			// above.
		}
	}

	private void rewriteClass(CtClass clazz) throws CannotCompileException
	{
		cusExpr.staticEdits(clazz);
		if (!clazz.isFrozen())
		{
			clazz.instrument(cusExpr);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javassist.Translator#start(javassist.ClassPool)
	 */
	@Override
	public void start(ClassPool pool) throws NotFoundException,
			CannotCompileException
	{
		// TODO Auto-generated method stub

	}

}
